#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/socket.h>

#define SERV_PORT 8888
#define BUF_SIZE 1024

int main(int argc, char *argv[]) {
    if (argc != 3) {
        printf("Usage: %s <server_ip> <port>\n", argv[0]);
        exit(1);
    }

    int server_port = atoi(argv[2]);
    int client_socket;
    struct sockaddr_in server_addr;

    // 创建一个TCP客户端套接字并连接到服务器
    client_socket = socket(AF_INET, SOCK_STREAM, 0);
    memset(&server_addr, 0, sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(server_port);
    inet_pton(AF_INET, argv[1], &server_addr.sin_addr);

    connect(client_socket, (struct sockaddr *)&server_addr, sizeof(server_addr));

    // 创建一个无限循环来读取用户输入的命令
    char buffer[BUF_SIZE];
    while (1) {
        printf("Enter command: ");
        fgets(buffer, BUF_SIZE, stdin);
        buffer[strlen(buffer) - 1] = '\0'; // 去掉末尾的换行符

        // 将输入的命令发送给服务器
        write(client_socket, buffer, strlen(buffer));

        // 如果用户输入的命令为quit，则退出循环并关闭连接
        if (strcmp(buffer, "quit") == 0) {
            break;
        }

        // 接收服务器返回的结果并在屏幕上显示
        memset(buffer, 0, sizeof(buffer));
        int n = read(client_socket, buffer, BUF_SIZE);
        if (n > 0) {
            buffer[n] = '\0';
            printf("Server response: \n%s\n", buffer);
        }
    }

    close(client_socket);
    return 0;
}
